package com.example.myapplication13_2;

import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.IOException;

/**
 * 音乐播放器主界面
 * 实现功能：
 * 1. 播放SD卡中的指定音频文件
 * 2. 播放/暂停/停止控制
 * 3. 循环播放控制
 * 4. 进度条显示和控制
 * 5. 播放时间显示
 */
public class MainActivity extends AppCompatActivity {
    // 播放模式常量
    private static final int MODE_ORDER = 0;     // 顺序播放
    private static final int MODE_REPEAT = 1;    // 循环播放
    private static final int PERMISSION_REQUEST_CODE = 123;

    // UI组件
    private Button btn1, button2, button3;
    private ImageButton btnPlay, btnStop, btnLoop;
    private SeekBar seekBar;
    private TextView tvCurrentTime, tvTotalTime, tvSongName;

    // 媒体播放相关
    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private boolean isPlaying = false;
    private int playMode = MODE_ORDER;
    private int currentSongIndex = 0;

    // 歌曲信息
    private final String[] songList = {"testmusic1.mp3", "testmusic2.mp3", "testmusic3.mp3"};
    private final String[] songNames = {"歌曲1", "歌曲2", "歌曲3"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkAndRequestPermissions();
    }

    /**
     * 权限检查和请求
     */
    private void checkAndRequestPermissions() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            initializeApp();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initializeApp();
            } else {
                Toast.makeText(this, "需要存储权限才能播放音乐", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    /**
     * 应用初始化
     */
    private void initializeApp() {
        initViews();
        initMediaPlayer();
        setupClickListeners();
        setupSeekBar();
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        // 音乐选择按钮
        btn1 = findViewById(R.id.btn1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);
        
        // 控制按钮
        btnPlay = findViewById(R.id.btn_play);
        btnStop = findViewById(R.id.btn_stop);
        btnLoop = findViewById(R.id.btn_loop);
        
        // 进度条和文本显示
        seekBar = findViewById(R.id.music_seekbar);
        tvCurrentTime = findViewById(R.id.music_current_time);
        tvTotalTime = findViewById(R.id.music_total_time);
        tvSongName = findViewById(R.id.txt_songName);
    }

    /**
     * 初始化MediaPlayer
     */
    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(mp -> handlePlaybackCompletion());
    }

    /**
     * 设置点击事件监听器
     */
    private void setupClickListeners() {
        // 音乐选择按钮
        btn1.setOnClickListener(v -> playSongAtIndex(0));
        button2.setOnClickListener(v -> playSongAtIndex(1));
        button3.setOnClickListener(v -> playSongAtIndex(2));

        // 播放控制按钮
        btnPlay.setOnClickListener(v -> handlePlayPause());
        btnStop.setOnClickListener(v -> handleStop());
        btnLoop.setOnClickListener(v -> togglePlayMode());
    }

    /**
     * 处理播放/暂停按钮点击
     */
    private void handlePlayPause() {
        if (mediaPlayer != null) {
            if (isPlaying) {
                pausePlayback();
            } else {
                startPlayback();
            }
            isPlaying = !isPlaying;
        }
    }

    /**
     * 处理停止按钮点击
     */
    private void handleStop() {
        if (mediaPlayer != null) {
            stopPlayback();
        }
    }

    /**
     * 开始播放
     */
    private void startPlayback() {
        mediaPlayer.start();
        btnPlay.setImageResource(R.drawable.pause);
        updateSeekBar();
    }

    /**
     * 暂停播放
     */
    private void pausePlayback() {
        mediaPlayer.pause();
        btnPlay.setImageResource(R.drawable.play);
    }

    /**
     * 停止播放
     */
    private void stopPlayback() {
        mediaPlayer.stop();
        try {
            mediaPlayer.prepare();
            resetPlaybackUI();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重置播放界面
     */
    private void resetPlaybackUI() {
        seekBar.setProgress(0);
        updateTimeText(0);
        isPlaying = false;
        btnPlay.setImageResource(R.drawable.play);
    }

    /**
     * 切换播放模式
     */
    private void togglePlayMode() {
        playMode = (playMode == MODE_ORDER) ? MODE_REPEAT : MODE_ORDER;
        mediaPlayer.setLooping(playMode == MODE_REPEAT);
        btnLoop.setImageResource(playMode == MODE_REPEAT ? R.drawable.repeat : R.drawable.orderplay);
        Toast.makeText(this, 
            playMode == MODE_REPEAT ? "循环播放模式" : "顺序播放模式", 
            Toast.LENGTH_SHORT).show();
    }

    /**
     * 处理播放完成事件
     */
    private void handlePlaybackCompletion() {
        if (playMode == MODE_ORDER) {
            playSongAtIndex((currentSongIndex + 1) % songList.length);
        } else {
            mediaPlayer.start();
        }
    }

    /**
     * 播放指定索引的歌曲
     */
    private void playSongAtIndex(int index) {
        currentSongIndex = index;
        playMusic(songList[index], songNames[index]);
    }

    /**
     * 播放指定的音乐文件
     */
    private void playMusic(String fileName, String songName) {
        try {
            File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard, fileName);
            
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.setDataSource(file.getAbsolutePath());
            mediaPlayer.prepare();
            mediaPlayer.start();
            
            updatePlaybackUI(songName);
        } catch (IOException e) {
            Toast.makeText(this, "播放失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 更新播放界面
     */
    private void updatePlaybackUI(String songName) {
        isPlaying = true;
        btnPlay.setImageResource(R.drawable.pause);
        tvSongName.setText("  正在播放: " + songName);
        seekBar.setMax(mediaPlayer.getDuration());
        updateTimeText(0);
        tvTotalTime.setText(formatTime(mediaPlayer.getDuration()));
        updateSeekBar();
    }

    /**
     * 设置进度条
     */
    private void setupSeekBar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    mediaPlayer.seekTo(progress);
                    updateTimeText(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    /**
     * 更新进度条
     */
    private void updateSeekBar() {
        if (mediaPlayer != null && isPlaying) {
            seekBar.setProgress(mediaPlayer.getCurrentPosition());
            updateTimeText(mediaPlayer.getCurrentPosition());
            handler.postDelayed(this::updateSeekBar, 1000);
        }
    }

    /**
     * 更新时间显示
     */
    private void updateTimeText(int milliseconds) {
        tvCurrentTime.setText(formatTime(milliseconds));
    }

    /**
     * 格式化时间
     */
    private String formatTime(int milliseconds) {
        int seconds = (milliseconds / 1000) % 60;
        int minutes = (milliseconds / 1000) / 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }
}